var mongoose=require('./mongoConn');
//var mongoose=require('mongoose');
//var config=require('../config');
//var mongodb = require('mongodb');
var Schema=mongoose.Schema;
/*var db=mongoose.createConnection(config.db_url);
db.on('error',function(error){
    db.close();
    console.log(error);
});

db.on('close', function () {
    db.open(config.db_url);
    console.log("重新连接mongo");
});*/

var materialSchema = new Schema({
    userid: String, //用户id
    imgs:[String]
});

//var Material = db.model("Material", materialSchema);
var Material = mongoose.model("Material", materialSchema);

Material.prototype.findAllMaterial=function(callback){
    Material.find({},function(err,datas){
        return callback(err,datas);
    })
}

Material.prototype.findMaterialById=function (userid,callback){
    Material.findOne({userid:userid}, function(err, datas){
        return callback(datas);
    });
}

Material.prototype.removeIdById=function (materialid,callback){
    Material.remove({_id:materialid}, function(err){
        return callback(err);
    });
}

Material.prototype.updateMaterialByUserId=function(userid,arr,callback){
    Material.update({userid:userid},arr,function(err){
    //Material.update({userid:userid},{$push:{imgs:{$each:arr}}},function(err){
        return callback(err);
    });
}

Material.prototype.findForPage=function(obj,callback){
    var q=obj.search||{};                                       //查询条件
    var col=obj.columns||{};                                    //返回字段
    var query=Material.find(q,col).skip(obj.page.skipFrom).limit(obj.page.limit);

    query.exec(function(err, datas) {
        if (err) {
            callback(err, null, null);
        } else {
            Material.count(q, function(err, count) {
                if (err) {
                    callback(err, null, null);
                } else {
                    var pageCount = Math.ceil(count / obj.page.limit);
                    callback(null,count,pageCount, datas);
                }
            });
        }
    });
}

module.exports = Material;